package com.ls.lsbase.frag;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatDialogFragment;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;


@SuppressLint("ValidFragment")
public class ImgPickFrag extends AppCompatDialogFragment implements TakePhoto.TakeResultListener, InvokeListener {
    private InvokeParam invokeParam;
    private TakePhoto takePhoto;
    private OnImgSelectListener listener;
    private int types, width, height;

    public interface OnImgSelectListener {
        void result(TResult result);
    }

    public void setListener(OnImgSelectListener listener) {
        this.listener = listener;
    }

    public ImgPickFrag(int type, int w, int h) {
        this.types = type;
        this.width = w;
        this.height = h;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        if (types == 1) {//选择相册
            selectImgs(getTakePhoto(), 1, 102400, width, height, 1);
        } else {
            selectImgs(getTakePhoto(), 2, 102400, width, height, 1);
        }
    }

    public void selectImgs(TakePhoto takePhoto, int type, int limit, int x, int y, int num) {
        //TODO
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        configCompress(takePhoto);
        configTakePhotoOption(takePhoto);
        switch (type) {
            case 1:
                if (num > 1) {
                    takePhoto.onPickMultipleWithCrop(limit, getCropOptions(x, y));//裁剪
//                    takePhoto.onPickMultiple(limit);//不裁剪
                    return;
                }
//                takePhoto.onPickFromDocumentsWithCrop(imageUri, getCropOptions(100, 100));   //裁剪
//                    takePhoto.onPickFromDocuments();//不裁剪
                //从相册
                takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions(width, height));
//                    takePhoto.onPickFromGallery();
                break;
            case 2:
                takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions(width, height));
//                takePhoto.onPickFromCapture(imageUri);
                break;
            default:
                break;
        }
    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);//是否使用自带相册(多选必须使用)
        builder.setCorrectImage(true);//纠正拍照的照片旋转角度
        takePhoto.setTakePhotoOptions(builder.create());
    }

    private void configCompress(TakePhoto takePhoto) {
//        takePhoto.onEnableCompress(null, false);//不压缩
        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(102400)//最大size(单位:B)
                .setMaxPixel(200)//宽高最大
                .enableReserveRaw(false)//保存原图
                .create();
        takePhoto.onEnableCompress(config, true);//压缩进度条
    }

    private CropOptions getCropOptions(int x, int y) {
//        return null;//不裁剪
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(x).setAspectY(y);
//            builder.setOutputX(x).setOutputY(y);
        builder.setWithOwnCrop(true);//使用自己裁剪
        return builder.create();
    }

    @Override
    public void takeCancel() {
        getDialog().dismiss();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        getDialog().dismiss();
    }

    @Override
    public void takeSuccess(TResult result) {
        listener.result(result);
        getDialog().dismiss();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }
}
